/*
 * RedisManager.cpp
 *
 *  Created on: Sep 19, 2016
 *      Author: root
 */
#include <stdlib.h>
#include "yRedisManager.h"
#include "../../third_part/xml/tinyxml2.h"
pthread_key_t RedisManager::key;
std::string RedisManager::ip;
int RedisManager::port;
using namespace tinyxml2;
void RedisManager::init() {
	pthread_key_create(&key, &RedisManager::closeKey);
	XMLDocument doc;
	doc.LoadFile("conf/global.xml");
	RedisManager::ip = std::string(doc.RootElement()->FirstChildElement("redis")->FirstChildElement("ip")->GetText());
	RedisManager::port = atoi(doc.RootElement()->FirstChildElement("redis")->FirstChildElement("port")->GetText());

}

redisContext* RedisManager::getConn() {
	redisContext*conn = (redisContext*) pthread_getspecific(key);
	if (conn) {
		redisReply * reply = (redisReply *) redisCommand(conn, "PING");
		if (reply) {
			freeReplyObject(reply);
			return conn;
		} else {
			int result = redisReconnect(conn);
			if (result == REDIS_OK) {
				return conn;
			} else {
				return NULL;
			}
		}

	} else {
		conn = redisConnect(RedisManager::ip.c_str(), RedisManager::port);
		if (conn && conn->err) {
			redisFree(conn);
			return NULL;
		}
		if (conn)
			pthread_setspecific(key, conn);
		return conn;
	}
}

void RedisManager::closeKey(void* thread_log) {
	redisContext*conn = (redisContext*) thread_log;
	if (conn)
		redisFree(conn);
}

void RedisManager::destory() {
	pthread_key_delete(key);
}
